package com.stars.easyms.redis.interceptor;

import com.stars.easyms.redis.annotion.RedisEval;
import com.stars.easyms.redis.exception.RedisInterceptorException;
import com.stars.easyms.redis.exception.RedisRuntimeException;
import com.stars.easyms.base.util.ReflectUtil;
import org.aopalliance.intercept.MethodInvocation;

import java.util.List;
import java.util.Map;

/**
 * <p>className: RedisEvalInterceptor</p>
 * <p>description: RedisEval注解拦截器</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-03-18 14:30
 */
public class RedisEvalInterceptor extends AbstractRedisInterceptor<RedisEval> {

    @Override
    protected Object invoke(MethodInvocation methodInvocation, RedisEval redisEval) throws RedisInterceptorException {
        if (isEnabled()) {
            String methodFullName = ReflectUtil.getMethodFullName(methodInvocation.getMethod());
            Map<String, List<String>> redisEvalMap = getRedisEvalKeyAndArg(methodInvocation);
            List<String> redisEvalKeyList = redisEvalMap.get("redisEvalKey");
            List<String> redisEvalArgList = redisEvalMap.get("redisEvalArg");
            if (redisEvalKeyList.size() > redisEvalArgList.size()) {
                throw new RedisRuntimeException("Method '{}' Number of RedisEvalKey({}) can't be greater than number of RedisEvalArg({})!", methodFullName, redisEvalKeyList, redisEvalArgList);
            }
            return easyMsRedisTemplate.execute(redisEval.script(), redisEvalKeyList, redisEvalArgList);
        }
        return proceed(methodInvocation);
    }

}